<template>
    <div class="white-box">
        <title-more title="批量修改会员" />
        <cell-tip show-more :datas="tipArrs" />
        <div class="mmy-btn">
            <el-upload
                ref="uploadFileRef"
                accept=".xlsx,.xls,.csv"
                :file-list="fileList_two"
                :action="actionImgUrl()"
                :auto-upload="false"
                :limit="1"
                :on-exceed="handleExceed_two"
                :on-remove="handleRemove_two"
                :on-change="fileChange_two"
            >
                <template #trigger>
                    <el-button type="primary">选择文件</el-button>
                </template>
                <el-button class="downs" type="warning" :loading="btn_loading" @click.stop="uploadFile">上传导入</el-button>
                <el-button class="downs" type="warning" @click.stop="clickDown">下载模板</el-button>
            </el-upload>
        </div>
    </div>
</template>

<script setup>
import { getCurrentInstance, ref, onMounted, onBeforeUnmount } from "vue"
import { genFileId } from "element-plus"
import TitleMore from "@components/title-more.vue"
import CellTip from "@components/cell-tip.vue"

const { proxy } = getCurrentInstance()

onMounted(() => {})

onBeforeUnmount(() => {
    uploadFileRef.value = null
})

const tipArrs = [
    "1、模板中的表头不可更改，表头行不可删除",
    "2、在表格模板中按相应字段填写信息，注意需要增加时填正整数（如：20），需要减少时填负数（如-10）",
    "3、填写完相关信息后选择文件上传导入",
    "4、请上传*.xlsx; *.xls; *.csv格式的文件",
    "5、操作步骤：先下载模板-选择编辑好的文件上传-最后上传导入该文件"
]

/**
 * 导入-批量修改会员
 * @param {Array} fileList_two 上传客户存储数组
 * @param {Function} actionImgUrl 阻止上传地址
 * @param {Function} handleRemove 文件状态移除时的钩子
 * @param {Function} fileChange 文件状态改变时的钩子
 * @param {Function} uploadFile 文件上传
 */
const uploadFileRef = ref(null)
const fileList_two = ref([])
const btn_loading = ref(false)
const fileChange_two = (file, fileArr) => {
    fileList_two.value = fileArr
}
const handleExceed_two = (files) => {
    uploadFileRef.value.clearFiles()
    const file = files[0]
    file.uid = genFileId()
    uploadFileRef.value.handleStart(file)
}
const handleRemove_two = () => {
    fileList_two.value = []
}
// 上传文件，生成文件路径
const uploadFile = () => {
    if (fileList_two.value.length == 0) {
        proxy.$message({ message: "请选择文件上传", type: "warning" })
        return
    }
    btn_loading.value = true
    let data = new FormData()
    data.append("excel", fileList_two.value[0].raw)
    data.append("type", "check") // [check:校验文件,import:导入文件]
    proxy.$axios
        .post("user/userImport", data)
        .then((res) => {
            fileList_two.value = []
            if (res.data.code == 0) {
                let result = res.data.data
                confirmUpload(result)
            } else {
                btn_loading.value = false
                proxy.$message({ message: res.data.msg, type: "error" })
            }
        })
        .catch((err) => {
            btn_loading.value = false
        })
}
// 同样的接口，上传文件路径，最终修改价格
function confirmUpload(params) {
    let data = new FormData()
    data.append("path", params.file)
    data.append("name", params.name)
    data.append("size", params.size)
    data.append("type", "import") // [check:校验文件,import:导入文件]
    proxy.$axios
        .post("user/userImport", data)
        .then((res) => {
            btn_loading.value = false
            if (res.data.code == 0) {
                uploadFileRef.value.clearFiles()
                dialogImportGoods.value = false
                proxy.$message({ message: "上传导入成功！", type: "success" })
            } else {
                proxy.$message({ message: res.data.msg, type: "error" })
            }
        })
        .catch((err) => {
            btn_loading.value = false
        })
}
// 上传地址
function actionImgUrl() {
    return ""
}

// 下载模板
const clickDown = () => {
    proxy.$axios
        .get("user/userImportTpl", {
            params: {},
            responseType: "blob",
        })
        .then(function (res) {
            let contentDisposition = res.headers["content-disposition"]
            let filename = decodeURI(contentDisposition.split("fileName=")[1] || contentDisposition.split("filename=")[1])
            let blob = new Blob([res.data], { type: res.headers["content-type"] })
            const url = window.URL.createObjectURL(blob)
            const link = document.createElement("a")
            link.href = url
            link.download = filename
            document.body.appendChild(link)
            link.click()
            URL.revokeObjectURL(url) // 释放内存
            document.body.removeChild(link)
        })
        .catch((err) => {})
}
</script>
<script>
export default {
    name: "MemberModify",
}
</script>
<style lang="less" scoped>
.mmy-btn {
    display: flex;
    margin-top: @margin-xl;
    .downs {
        margin-left: @margin-mdl;
    }
}
:deep(.el-upload-list) {
    width: 500px;
}
</style>
